package com.zzyl.intercept;

import com.zzyl.constant.UserCacheConstant;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.HttpStatus;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Set;

import static com.zzyl.constant.Constants.*;

@Component
@Slf4j
public class AdminUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties properties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从header中获取用户信息
        String token = request.getHeader(USER_TOKEN);
        if(StringUtils.isEmpty(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = JwtUtil.parseJWT(properties.getBase64EncodedSecretKey(), token);
            Long userId = claims.get(JWT_USERID, Long.class);
            String username = claims.get(JWT_USERNAME, String.class);
            log.info("token中解析userId:{} username:{}", userId, username);
//            // 从redis中获取用户有权限的url
//            Set<String> urlList = redisTemplate.opsForSet().members(UserCacheConstant.USER_RESOURCE_LIST + userId);
//            if (CollectionUtils.isEmpty(urlList)) {
//                response.setStatus(HttpStatus.FORBIDDEN);
//                return false;
//            }
//            String requestUrl = request.getRequestURI();
//            String requestMethod = request.getMethod().toUpperCase();
//            boolean hasPermission = false;
//            // 判断当前的请求地址是否在用户的有权限的url列表中
//            for (String urlpattern : urlList) {
//                boolean match = antPathMatcher.match(urlpattern, requestMethod + requestUrl);
//                if (match) {
//                    hasPermission = true;
//                    break;
//                }
//            }
//            if(!hasPermission){
//                response.setStatus(HttpStatus.FORBIDDEN);
//                return false;
//            }
            // 把用户信息保存到ThreadLocal
            UserThreadLocal.setSubject(""+userId);
            return true;
        }catch(Exception e){
            log.info(e.getMessage(), e);
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
